<?php

namespace App\Service\Third;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Helpers\Helper;
use App\Model\PaycallbackLog;
use App\Model\PayOrder;
use App\Model\Service\PaycallbackService;

/**
 * 苹果内购验证回调
 */
class ApplePayCallbackService extends PayBaseService
{
    protected function RoVerifyList()
    {
        return [
            'order_id' => 'required|string',
            'apple_receipt' => 'required|string'
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        //苹果内购的验证收据
        $receiptData = $this->request->input('apple_receipt', '');
        $orderId = $this->request->input('order_id', '');

        //查询订单记录
        $order = PayOrder::getByOrderId($userId, $orderId);
        if (!$order || $order['status'] != PayOrder::STATUS_ING) {
            return $this->setError(ErrorCode::ORDER_NOT_EXISTS, '查不到该订单, 或订单已处理!');
        }
        if (empty($receiptData)) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '参数不正确');
        }

        //支付回调请求日志
        PaycallbackLog::addRecord(PayOrder::CHANNEL_APPLE, $orderId, $receiptData);

        // 获取校验结果
        $result = $this->validateApplePay($receiptData);

        if (!$result || !is_array($result) || !isset($result['status'])) {
            return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, '获取数据失败，请重试');
        }
        //如果校验失败
        if ($result['status'] != 0) {
            return $this->setError(ErrorCode::APPLE_PAY_VERIFY_ERR, '验证失败!');
        }

        //验证成功
        if ($result['status'] == 0) {
            $transaction_ids = []; //用来收集需要关闭的transaction_id
            //遍历未结束交易的列表（in_app）
            foreach ($result['receipt']['in_app'] as $product) {
                $subject = ConfigUtil::getRecharge($product['product_id'], PayOrder::CHANNEL_APPLE);
                //不管当前交易是否已经处理过，都要返回给客户端结束交易
                //支付回调
                PaycallbackService::successCallback($order['out_trade_no'], $this->parsePayMoney($subject['rmb']), PayOrder::CHANNEL_APPLE);
            }
            //返回给客户端需要结束交易的transaction_id列表
            return [
                'result' => 1,
                'tip' => '恭喜您支付成功!',
                'recharge_coin' => $order['recharge_coin'],
            ];
        }
    }

    /**
     * 解析支付总金额（分）
     */
    protected function parsePayMoney($callbackAmount = 0.0)
    {
        return $callbackAmount * 100;
    }

    /**
     * 验证AppStore内付
     * @param  string $receipt_data 付款后凭证
     * @return array                验证是否成功
     */
    protected  function validateApplePay($receiptData)
    {
        /**
         * 21000 App Store不能读取你提供的JSON对象
         * 21002 receipt-data域的数据有问题
         * 21003 receipt无法通过验证
         * 21004 提供的shared secret不匹配你账号中的shared secret
         * 21005 receipt服务器当前不可用
         * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
         * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
         * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
         */

        $POSTFIELDS = '{"receipt-data":"' . $receiptData . '"}';
        // $POSTFIELDS = ['receipt-data' => $receiptData];
        if (config('pay.apple.sandbox')) {
            // 请求验证-沙盒
            $data = Helper::curlRequest('https://sandbox.itunes.apple.com/verifyReceipt', $POSTFIELDS);
        } else {
            // 请求验证
            $data = Helper::curlRequest('https://buy.itunes.apple.com/verifyReceipt', $POSTFIELDS);
        }
        log_info(__CLASS__ . "==validateApplePay=={$data}");
        return $data ? @json_decode($data, true) : '';
    }
}
